import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './filters/http-exception.filter';
import { TransformInterceptor } from './interceptors/transform.interceptor';
import { swaggerConfig, SWAGGER_API_ROOT } from './config/swagger.config';
import { getLocalIp } from './utils/network.util';
import { StartupLoggerService } from './services/startup-logger.service';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  // 使用 NestExpressApplication 类型
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: ['error', 'warn', 'log', 'debug', 'verbose'], // 启用所有日志级别
  });
  const startupLogger = new StartupLoggerService();
  // 启用 CORS
  app.enableCors();
  // 设置全局路由前缀
  // app.setGlobalPrefix('api');
  app.setGlobalPrefix('api', {
    exclude: ['/static', '/static/(.*)', '/favicon.ico'],
  });

  // 全局验证管道
  app.useGlobalPipes(new ValidationPipe({
    transform: true,
    whitelist: true,
  }));

  // 全局异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());

  // 全局响应拦截器
  app.useGlobalInterceptors(new TransformInterceptor());

  // Swagger文档
  const document = SwaggerModule.createDocument(app, swaggerConfig);
  document.security = [{ 'JWT-auth': [] }];
  SwaggerModule.setup(SWAGGER_API_ROOT, app, document);

  const port = Number(process.env.PORT) || 3001;
  const host = 'localhost';
  const localIp = getLocalIp();
  await app.listen(port);
  startupLogger.logApplicationStartup(host, port, localIp, SWAGGER_API_ROOT);
}
bootstrap();
